package com.vctgo.system.config;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class DynamicDataSourceAspect {

    private static final ExpressionParser PARSER = new SpelExpressionParser();

    @Before("@within(ds) || @annotation(ds)")
    public void before(JoinPoint joinPoint, DS ds) {
        // 获取方法上的 @DS 注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        DS dsAnnotation = AnnotationUtils.getAnnotation(method, DS.class);
        if (dsAnnotation == null) {
            dsAnnotation = AnnotationUtils.findAnnotation(joinPoint.getTarget().getClass(), DS.class);
        }
        if (dsAnnotation == null) {
            return;
        }

        // 解析 SpEL 表达式（例如 "#tenantId"）
        String spelExpression = dsAnnotation.value();
        if (!"#tenantId".equals(spelExpression)) {
            return;
        }
        StandardEvaluationContext context = new StandardEvaluationContext();

        // 绑定请求头中的 tenantId 到 SpEL 上下文
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String tenantId = request.getHeader("tenant-id");
        context.setVariable("tenantId", StringUtils.isNotBlank(tenantId) && !"9999".equals(tenantId) ? tenantId : "master");

        // 解析表达式
        Expression expression = PARSER.parseExpression(spelExpression);
        String dataSourceKey = expression.getValue(context, String.class);

        // 设置数据源键
        DynamicDataSourceContextHolder.push(dataSourceKey);
    }

    @After("@within(ds) || @annotation(ds)")
    public void after(JoinPoint joinPoint, DS ds) {
        // 清除数据源键
        DynamicDataSourceContextHolder.poll();
    }
}
